/**
 *
 * 移除dom的某个属性
 * @param {Node} node
 * @param {String} attrName
 * @return {String}
 */
export const removeAttr = (node, attrName) => {
  const _attr = attrName
  const val = node.getAttribute(_attr)
  if (val !== null) {
    node.removeAttribute(_attr)
  }
  return val
}

/**
 *
 * 移除一个dom元素
 * @param {Element} el
 */
export const remove = (el) => {
  el.parentNode.removeChild(el)
}

/**
 * 是否有class
 *
 * @param {Element} el
 * @param {string} cls
 */
export const hasClass = (el, cls) => el.className && el.className.includes(cls)

/**
 * 添加class
 *
 * @param {Element} el
 * @param {string} cls
 */
export const addClass = (el, cls) => {
  if (el.classList) {
    el.classList.add(cls)
  } else {
    const cur = ` ${(el.getAttribute('class') || '')} `
    if (cur.indexOf(` ${cls} `) < 0) {
      el.setAttribute('class', (cur + cls).trim())
    }
  }
}
/**
 * 移除样式
 *
 * @param {Element} el
 * @param {string} cls
 */
export const removeClass = (el, cls) => {
  if (el.classList) {
    el.classList.remove(cls)
  } else {
    let cur = ` ${(el.getAttribute('class') || '')} `
    const tar = ` ${cls} `
    while (cur.indexOf(tar) >= 0) {
      cur = cur.replace(tar, ' ')
    }
    el.setAttribute('class', cur.trim())
  }
}

/**
 * 获取单个dom或者某个dom之后的dom
 *
 * @param {string} str
 * @param {string} dom
 * @return {dom}或{Array}
 */
export const $ = (str, dom) => {
  if (!dom) {
    return document.queryselector(str)
  }
  return dom.queryselector(str)
}

/**
 * 获取多个dom或者某个dom之后的dom
 *
 * @param {string} str
 * @param {string} dom
 * @return {Array}
 */
export const $$ = (str, dom) => {
  if (!dom) {
    return document.queryselectorAll(str)
  }
  return dom.queryselectorAll(str)
}

/**
 * 获取离元素最近的含有某个class的父级元素
 *
 * @param {Element} node
 * @param {string} parentClass
 * @return {Element}
 */
export const getParentNode = (node, parentClass) => {
  const parentNode = node.parentNode
  if (node && hasClass(node, parentClass)) {
    return node
  }
  if (parentNode && parentNode.targetName !== 'body') {
    return getParentNode(parentNode)
  }
  return null
}
